package main

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"os"
)

func main() {
	r := gin.Default()

	r.POST("/upload", func(c *gin.Context) {
		form, err := c.MultipartForm()
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    400,
				"message": fmt.Sprintf("Error parsing form: %s", err.Error()),
			})
			return
		}

		for _, fileHeaders := range form.File {
			for _, file := range fileHeaders {
				// Save the uploaded file
				if err := c.SaveUploadedFile(file, "./uploads/"+file.Filename); err != nil {
					c.JSON(http.StatusInternalServerError, gin.H{
						"code":    500,
						"message": fmt.Sprintf("Error parsing form: %s", err.Error()),
					})
					return
				}
			}
		}

		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "Files uploaded successfully",
		})
	})

	r.GET("/download", func(c *gin.Context) {
		filePath := "example.txt" // Replace with the path to your file

		file, err := os.Open(filePath)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"code":    500,
				"message": fmt.Sprintf("Error opening file: %s", err),
			})
			return
		}
		defer file.Close()

		// Set Content-Disposition header to indicate file name
		c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", "example.txt"))

		// Set Content-Type header to indicate binary data
		c.Header("Content-Type", "application/octet-stream")

		// Copy the file content to the response writer
		_, err = io.Copy(c.Writer, file)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"code":    500,
				"message": fmt.Sprintf("Error copying file content: %s", err),
			})
			return
		}
	})

	r.POST("/user", func(c *gin.Context) {
		s := &struct {
			Id   int    `form:"id" json:"id" binding:"required"`
			Name string `form:"name" json:"name" binding:"required"`
		}{}
		data, err := c.GetRawData()
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":    400,
				"message": fmt.Sprintf("Error parsing form: %s", err.Error()),
			})
			return
		}
		json.Unmarshal(data, s)
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": s,
		})
	})

	r.Run(":8080")
}
